package com.zhugang.week05;

/**
 * @program algorithms
 * @description: findPeakElement
 * @author: chanzhugang
 * @create: 2022/07/06 14:08
 */
public class FindPeakElement {

    public static void main(String[] args) {
        FindPeakElement findPeakElement = new FindPeakElement();
        int[] nums = new int[]{1};
        int index = findPeakElement.findPeakElement(nums);
        System.out.println(index);
    }

    /**
     * 162 寻找峰值
     *
     * @param nums
     * @return
     */
    public int findPeakElement(int[] nums) {
        // 多个if 不管前面ture与否后面的多执行
        // else if 如果前面一个成立，后面的都不执行

        // 多个峰值
        int low = 0;
        int high = nums.length - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (low == high) {
                // [2], 数组只有一个元素时
                return mid;
            }

            if (mid == 0) {
                if (nums[mid] > nums[mid + 1]) {
                    return mid;
                } else {
                    low = mid + 1;
                }

            } else if (mid == nums.length - 1) {
                if (nums[mid] > nums[mid - 1]) {
                    return mid;
                } else {
                    high = mid - 1;
                }
            } else if (nums[mid] > nums[mid - 1] && nums[mid] > nums[mid + 1]) {
                // 峰值
                return mid;
            } else if (nums[mid] < nums[mid + 1]) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return -1;
    }
}